//
//  LWUserAccount.swift
//  Swift_Weibo_HLW
//
//  Created by huanglinwang on 16/9/22.
//  Copyright © 2016年 Linwang. All rights reserved.
//

import UIKit

//存储或者读取沙盒归档路径
private let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
//用户账号模型
class LWUserAccount: NSObject,NSCoding {
//string	用户授权的唯一票据
    var access_token :String?
    //access_token的生命周期，单位是秒数
    var expires_in : TimeInterval = 0 {
        didSet{
            //过期时间 = 当前时间 + 过去秒数
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
//    access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
//    var remind_in : String?
    //授权用户的UID，本字段只是为了方便开发者，减少一次user/show接口调用而返回的，第三方应用不能用此字段作为用户登录状态的识别，只有access_token才是用户授权的唯一票据。
    //过期时间
    var expiresDate: Date?
    //uid
    var uid : Int64 = 0
    // 用户名
    var name: String?
    // 图片链接
    var profile_image_url: String?
    //kvc 字典转模型
    init(dict :[String: Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    //防止不匹配
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
    // MARK: -  归档与解档
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(profile_image_url, forKey: "profile_image_url")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey:"access_token" ) as? String
        expiresDate = aDecoder.decodeObject(forKey:"expiresDate" ) as? Date
        //直接Int64
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        profile_image_url = aDecoder.decodeObject(forKey: "profile_image_url") as? String
    }
    //保存当前用户对象
    func saveUserAccount() -> () {
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    //从指定的沙盒加载用户对象
    class func loadUserAccount() -> LWUserAccount? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? LWUserAccount
    }
}







